import axios from 'axios'
import qs from 'qs'
import { dateFormat } from 'js-dateformat'

axios.defaults.baseURL = '/api'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.timeout = 10000
let loginUrl = '/login.html'

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前处理
    if (localStorage.getItem('px_user_tag')) {
        config.headers['zygx-tag'] = localStorage.getItem('px_user_tag')
        return config
    } else {
        location.href = loginUrl
    }
}, function (error) {
    return Promise.reject(error)
})

// 响应拦截
axios.interceptors.response.use(function (response) {
	// 处理响应数据
	if (response.status === 200) {
        if (response.data.code === '002') {
            location.href = loginUrl
        } else {
            return Promise.resolve(response)
        }
	} else {
		return Promise.reject(response)
	}
}, function (error) {
	// 处理响应失败
	return Promise.reject(error)
})

/* 时间格式化 */
export function formatDate (date) {
    if (date !== '' && date != null) {
        if (typeof date === 'string') {
            return dateFormat(new Date(date), 'yyyy-mm-dd HH:MM:ss')
        } else {
            return dateFormat(date, 'yyyy-mm-dd HH:MM:ss')
        }
    } else {
        return null
    }
}

export function get (url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
			params
        }).then(res => {
			resolve(res.data)
        }).catch(err => {
			reject(err)
        })
    })
}

/* 对象深拷贝 */
export function copy (obj) {
    return JSON.parse(JSON.stringify(obj))
}

export function post (url, params) {
    return new Promise((resolve, reject) => {
        axios.post(url, qs.stringify(params))
        .then(res => {
            resolve(res.data)
        })
        .catch(err => {
            reject(err)
        })
    })
}

/**
 * 文件导出
 * @param url
 * @param params
 * @param filename 文件名称
 */
export function exportData (url, params, filename) {
    axios.get(url, {
        params,
        responseType: 'blob'
    }).then(res => {
        let link = document.createElement('a')
        link.href = window.URL.createObjectURL(new Blob([res.data]))
        link.target = '_blank'
        link.download = filename
        document.body.appendChild(link)
        link.click()
        URL.revokeObjectURL(link.href)
        document.body.removeChild(link)
    }).catch(err => {
        console.error(err)
    })
}

export let strUtils = {}
strUtils.isNotEmpty = function (str) {
    if (str === null || str.trim() === '' || typeof str === 'undefined') {
        return false
    } else {
        return true
    }
}

export let sysConf = {
    sucCode: '000'
}
